// 获取应用实例
const app = getApp()

Page({
  data: {
    urlPath:'../index/index.js',
    loadingFlag:'',
    devices: ["设备1", "设备2", "设备3"],
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') ,
    inputValue:'',
    placeholder:'Search for your device name',
  },

  handleSearch: function (e) {
    const devices = e.detail.devices; 
    wx.navigateTo({
      url: `../selectResult/selectResult?devices=${JSON.stringify(devices)}`,
    });
  },
  onTextareaFocus: function (e) {
    this.setData({
      placeholder: '', 
    });
  },

  
  onTextareaBlur: function (e) {
    this.setData({
      placeholder: 'Search for your device name', 
    });
  },

  onTextareaInput: function (e) {
    this.setData({
      inputValue: e.detail.value, 
    });
  },

  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onShow(){
    this.onLoad();
  },
  
  onLoad() {
    let that = this;
    this.setData({
      loadingFlag:true
    });
    wx.request({
      url: 'http://114.132.70.44:2000/get_device',
      success (res) {
        that.setData({
          devices:res.data.payload
        })
        console.log('that.devices',that.data.devices)
      }
    },
    )
    setTimeout(() => this.setData({
      loadingFlag:false
    }), 500)
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  getUserProfile(e) {
    wx.getUserProfile({
      desc: '展示用户信息', 
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  gotoscene: function () {
    wx.navigateTo({
      url: '../manager/manager?device=' + this.data.device
    });
  },
  gotoscene: function (event) {
    const device = event.currentTarget.dataset.device;
    wx.navigateTo({
      url: `../manager/manager?device=${device}`
    });
  },
  gotoadd: function () {
    let count = this.data.devices.length;
    count++;
    this.data.devices.push("设备"+count);
    this.onLoad();
    wx.navigateTo({
      url: '../devicechoose/devicechoose',
    })
  },
  delete(event) {
    const index = event.currentTarget.dataset.index; 
    const { devices } = this.data;
    if (index >= 0 && index < devices.length) {
      wx.request({
        url: 'http://114.132.70.44:2000/del_device',
        method:'POST',
        data:{'id':devices[index]}
      })
      devices.splice(index, 1);
      this.setData({
        devices: devices
      });
    }
  },
})
